package org.jetlinks.pro.clickhouse.engine;

import lombok.Getter;
import lombok.Setter;

import java.util.function.Consumer;

/**
 * CH 表引擎配置类
 *
 * @author zhouhao
 * @since 1.10
 */
@Getter
@Setter
public class ClickHouseEngineTemplate {

    /**
     * 引擎类型
     */
    private EngineType engine = EngineType.MergeTree;

    /**
     * 引擎类型为mergeTree时有效
     */
    private MergeTree mergeTree = new MergeTree();

    /**
     * 引擎类型为replicatedMergeTree时有效
     */
    private ReplicatedMergeTree replicatedMergeTree = new ReplicatedMergeTree();

    /**
     * 引擎类型为distributed时有效
     */
    private Distributed distributed = new Distributed();


    /**
     * 获取当前的表引擎
     *
     * @return 当前的表引擎
     */
    public Engine currentEngine() {
        switch (engine) {
            case ReplicatedMergeTree:
                return replicatedMergeTree;
            case Distributed:
                return distributed;
            default:
                return mergeTree;
        }
    }


    public EngineBuilder builder() {
        Engine engine = currentEngine().copy();
        return new EngineBuilder() {
            @Override
            public <T extends Engine> EngineBuilder when(Class<T> engineType, Consumer<T> consumer) {
                if (engineType.isInstance(engine)) {
                    consumer.accept(engineType.cast(engine));
                }
                return this;
            }

            @Override
            public Engine build() {
                return engine;
            }
        };
    }

}
